package cn.conac.rc.gateway.modules.ofs.rest;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.conac.rc.framework.utils.BeanMapper;
import cn.conac.rc.framework.utils.RestClientException;
import cn.conac.rc.framework.utils.ResultPojo;
import cn.conac.rc.gateway.modules.ofs.contsant.Contsants;
import cn.conac.rc.gateway.modules.ofs.entity.AppFilesEntity;
import cn.conac.rc.gateway.modules.ofs.entity.ApprovalEntity;
import cn.conac.rc.gateway.modules.ofs.entity.OrgCombinEntity;
import cn.conac.rc.gateway.modules.ofs.entity.OrgStatusEntity;
import cn.conac.rc.gateway.modules.ofs.service.OrgCommonService;
import cn.conac.rc.gateway.modules.ofs.service.VHistApprovalService;
import cn.conac.rc.gateway.modules.ofs.vo.OperationStatusVo;
import cn.conac.rc.gateway.modules.ofs.vo.OrgChangeVo;
import cn.conac.rc.gateway.modules.ofs.vo.OrgRevVo;
import cn.conac.rc.gateway.security.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping(value="ofs/")
@Api(tags = "部门共通信息", description = "三定信息")
public class OrgCommonController {

	@Autowired
	OrgCommonService service;
	
	@Autowired
	VHistApprovalService   vHistApprovalService;

	@ApiOperation(value = "物理删除历史沿革节点信息和待提交节点（最新节点场合部门库信息不删除只是对baseId置空）", httpMethod = "POST",  notes = "根据baseId物理删除历史沿革节点信息（最新节点场合部门库信息不删除只是对baseId置空）")
	@RequestMapping(value = "3/{baseId}/d", method = RequestMethod.POST)
	public JSONObject cudPreOrgDelete(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "baseId", required = true) @PathVariable("baseId") String baseId) {
		
		return service.delete(baseId);
	}
	
	@ApiOperation(value = "物理删除审核通过三定信息（部门库信息不删除只是对baseId置空）", httpMethod = "POST",  notes = "根据部门库ID物理删除审核通过三定信息（部门库信息不删除只是对baseId置空）")
	@RequestMapping(value = "3/audited/{orgId}/d", method = RequestMethod.POST)
	public JSONObject cudOrgAuditedDelete(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "orgId", required = true) @PathVariable("orgId") String orgId) {
		
		return service.orgAuditeddelete(orgId);
	}
	
	@ApiOperation(value = "部门变更", httpMethod = "POST",  notes = "部门变更")
	@RequestMapping(value = "3/change", method = RequestMethod.POST)
	public Object cudOrgChange(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "部门状态信息的entity", required = true)  @RequestBody Map<String, Object> entityMap) {
		
		ResultPojo resultInfo = new ResultPojo();
		
		// 获得操作相关状态信息
		OperationStatusVo operationStatusVoInfo=  new OperationStatusVo();
       BeanMapper.copy(entityMap.get("operationStatus"), operationStatusVoInfo);

		// 获得部门状态信息
        OrgStatusEntity statusEntityInfo=  new OrgStatusEntity();
        BeanMapper.copy(entityMap.get("statusEntity"), statusEntityInfo);
        String updateType = statusEntityInfo.getUpdateType();
        if(null == updateType){
        	 //变更类型(updateType)为null场合返回错误信息
	       	  resultInfo.setCode(ResultPojo.CODE_FAILURE);
	          resultInfo.setMsg("[ the updateType of statusEntityInfo is null] in function of orgChange " + ResultPojo.MSG_FAILURE);
	       	  resultInfo.setResult(null);
	       	  return resultInfo;
        }
        // 设置登录用户ID
		 statusEntityInfo.setRegUserId(UserUtils.getCurrentUser().getId());
		 // 设置创建时间
		 statusEntityInfo.setCreateTime(new Date());
		 // 设置更新用户ID为null
		 statusEntityInfo.setUpdateUserId(null);

        // 参数值验证
        if((Contsants.ORG_CHANGE_MODEL_CURR.equals(operationStatusVoInfo.getOperation()) ||
            		Contsants.ORG_CHANGE_MODEL_INPUT.equals(operationStatusVoInfo.getOperation()))
            		&&  null == operationStatusVoInfo.getOrgId() ){
        	 //变更类型(updateType)为null场合返回错误信息
	       	  resultInfo.setCode(ResultPojo.CODE_FAILURE);
	          resultInfo.setMsg("[ the orgId of operationStatusVoInfo is null] in function of orgChange " + ResultPojo.MSG_FAILURE);
	       	  resultInfo.setResult(null);
	       	  return resultInfo;
        }
        
        if(Contsants.ORG_CHANGE_MODEL_HIST.equals(operationStatusVoInfo.getOperation()) 
        		&&  null == operationStatusVoInfo.getBaseId() ){
        	 //变更类型(updateType)为null场合返回错误信息
	       	  resultInfo.setCode(ResultPojo.CODE_FAILURE);
	          resultInfo.setMsg("[ the baseId of operationStatusVoInfo is null] in function of orgChange " + ResultPojo.MSG_FAILURE);
	       	  resultInfo.setResult(null);
	       	  return resultInfo;
        }
        if(Contsants.ORG_CHANGE_MODEL_CURR.equals(operationStatusVoInfo.getOperation())) {
     	    // 部门管理变更
     	    JSONArray vHistApprovaList  = new JSONArray();
 	   		// 历史沿革撤并场合判断是否有录入三定信息
 	   		JSONObject  vHistApprovalJsonObj =  vHistApprovalService.historyList(operationStatusVoInfo.getOrgId().toString());
 	   		// 判断取得批文历史数据是否成功失败
 	   	  	 if (ResultPojo.CODE_SUCCESS.equals(vHistApprovalJsonObj.getString("code"))) {
 	   	  		vHistApprovaList = vHistApprovalJsonObj.getJSONArray("result");
 	   	  		if(vHistApprovaList.size() == 0) {
 	   	  			// 取得批文历史数据列表失败场合
 	   				resultInfo.setCode(ResultPojo.CODE_NULL_ERR);
 	   				resultInfo.setMsg("根据部门库ID【" + operationStatusVoInfo.getOrgId().toString()+  "】查找部门基本信息的" + ResultPojo.MSG_NULL_ERR + "请先录入完整的部门的三定信息" );
 	   				
 	   				return resultInfo;
 	   	  		}
 	   	  	 } else {
 	   	  		 	// 取得批文历史数据列表失败场合
 	   				resultInfo.setCode(vHistApprovalJsonObj.getString("code"));
 	   				resultInfo.setMsg("[vHistApprovalService.historyList] in function of orgRevSave (OrgId="  + operationStatusVoInfo.getOrgId().toString()+
 	   										" error occured) " + ResultPojo.MSG_FAILURE + "【"  + vHistApprovalJsonObj.getString("msg") + "】" );
 	   				
 	   				return resultInfo;
 	   	  	 }
        } 
		 OrgChangeVo orgChangeVo =new OrgChangeVo();
		 orgChangeVo.setOperationStatusVo(operationStatusVoInfo);
		 orgChangeVo.setOrgStatusEntity(statusEntityInfo);
		 
		return service.orgChange(orgChangeVo);
		
	}
	
	@ApiOperation(value = "部门撤并信息保存", httpMethod = "POST",  notes = "部门撤并信息保存")
	@RequestMapping(value = "3/{orgId}/rev/c", method = RequestMethod.POST)
	public Object cudOrgRevSave(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "orgId", required = true) @PathVariable("orgId") String orgId, 
			@ApiParam(value = "部门状态信息的entity", required = true)  @RequestBody Map<String, Map<String, Object>> entityMap) {
		
		ResultPojo resultInfo = new ResultPojo();
		JSONArray vHistApprovaList  = new JSONArray();
		// 历史沿革撤并场合判断是否有录入三定信息
		JSONObject  vHistApprovalJsonObj =  vHistApprovalService.historyList(orgId);
		// 判断取得批文历史数据是否成功失败
	  	 if (ResultPojo.CODE_SUCCESS.equals(vHistApprovalJsonObj.getString("code"))) {
	  		vHistApprovaList = vHistApprovalJsonObj.getJSONArray("result");
	  		if(vHistApprovaList.size() == 0) {
	  			// 取得批文历史数据列表失败场合
				resultInfo.setCode(ResultPojo.CODE_NULL_ERR);
				resultInfo.setMsg("根据部门库ID【" + orgId+  "】查找部门基本信息的" + ResultPojo.MSG_NULL_ERR + "请先录入完整的部门的三定信息" );
				
				return resultInfo;
	  		}
	  	 } else {
	  		 	// 取得批文历史数据列表失败场合
				resultInfo.setCode(vHistApprovalJsonObj.getString("code"));
				resultInfo.setMsg("[vHistApprovalService.historyList] in function of orgRevSave (OrgId="  + orgId+
										" error occured) " + ResultPojo.MSG_FAILURE + "【"  + vHistApprovalJsonObj.getString("msg") + "】" );
				
				return resultInfo;
	  	 }
	  	 
		 String bianBanFlag ="0";
		OrgRevVo orgRevVo = new OrgRevVo();
		
		// 获得部门批文信息
	   	ApprovalEntity approvalEntityInfo = new ApprovalEntity();
	   	BeanMapper.copy(entityMap.get("approvalEntity"), approvalEntityInfo);
	   	 
	   	// 获得部门批文文件信息
	   	AppFilesEntity appFilesEntityInfo = new AppFilesEntity();
	    BeanMapper.copy(entityMap.get("appFilesEntity"), appFilesEntityInfo);
        
        // 获得部门合并信息
	    Object combinOrgIdsObj  =   entityMap.get("combinEntityList").get("combinOrgIds");
	    String combinOrgIds = null;
	    if(null != combinOrgIdsObj){
	    	combinOrgIds = combinOrgIdsObj.toString();
	    }
        List<OrgCombinEntity> combinEntityList=  new ArrayList<OrgCombinEntity>();
        OrgCombinEntity orgCombinEntity = null;
        
        if( StringUtils.isNotEmpty(combinOrgIds)) {
	        String[] orgIds = combinOrgIds.split(",");
	        for (int i=0; i < orgIds.length; i++) {
	        	if(StringUtils.isNotEmpty(orgIds[i])) {
		        	orgCombinEntity = new OrgCombinEntity();
		        	orgCombinEntity.setOrgId(orgIds[i]);
		        	combinEntityList.add(orgCombinEntity);
	        	}
	        }
        }

        // 获得部门状态信息
        OrgStatusEntity statusEntityInfo=  new OrgStatusEntity();
        BeanMapper.copy(entityMap.get("statusEntity"), statusEntityInfo);
        // 设置登录用户ID
		 statusEntityInfo.setRegUserId(UserUtils.getCurrentUser().getId());
		// 设置创建时间
		 statusEntityInfo.setCreateTime(new Date());
		 // 设置用户更新ID
		 statusEntityInfo.setUpdateUserId(null);
		 
		 orgRevVo.setApprovalEntity(approvalEntityInfo);
		 orgRevVo.setOrgCombinList(combinEntityList);
		 orgRevVo.setOrgStatusEntity(statusEntityInfo);
		 orgRevVo.setAppFilesEntity(appFilesEntityInfo);

		 if(UserUtils.isBianBan()) {
			 bianBanFlag = "1";
		 }
		return service.orgRevSave(orgId, bianBanFlag, orgRevVo);
		
	}
	
	@ApiOperation(value = "部门撤并信息更新", httpMethod = "POST", notes = "部门撤并信息更新")
	@RequestMapping(value = "3/{baseId}/rev/u", method = RequestMethod.POST)
	public JSONObject cudOrgRevUpdate(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "baseId", required = true) @PathVariable("baseId") String baseId, 
			@ApiParam(value = "部门撤并的entityMap", required = true)  @RequestBody Map<String, Map<String, Object>> entityMap) {
		
		OrgRevVo orgRevVo = new OrgRevVo();
	
		// 获得部门批文信息
	   	ApprovalEntity approvalEntityInfo = new ApprovalEntity();
	   	BeanMapper.copy(entityMap.get("approvalEntity"), approvalEntityInfo);
	   	 
	   	// 获得部门批文文件信息
	   	AppFilesEntity appFilesEntityInfo = new AppFilesEntity();
	    BeanMapper.copy(entityMap.get("appFilesEntity"), appFilesEntityInfo);
        
	    // 获得部门合并信息
	    String combinOrgIds = entityMap.get("combinEntityList").get("combinOrgIds").toString();
        List<OrgCombinEntity> combinEntityList=  new ArrayList<OrgCombinEntity>();
        OrgCombinEntity orgCombinEntity = null;
        
        if( StringUtils.isNotEmpty(combinOrgIds)) {
	        String[] orgIds = combinOrgIds.split(",");
	        for (int i=0; i < orgIds.length; i++) {
	        	if(StringUtils.isNotEmpty(orgIds[i])) {
		        	orgCombinEntity = new OrgCombinEntity();
		        	orgCombinEntity.setOrgId(orgIds[i]);
		        	combinEntityList.add(orgCombinEntity);
	        	}
	        }
        }

        // 获得部门状态信息
        OrgStatusEntity statusEntityInfo=  new OrgStatusEntity();
        BeanMapper.copy(entityMap.get("statusEntity"), statusEntityInfo);
        // 设置登录用户ID
		 statusEntityInfo.setUpdateUserId(UserUtils.getCurrentUser().getId());
		 
		 orgRevVo.setApprovalEntity(approvalEntityInfo);
		 orgRevVo.setOrgCombinList(combinEntityList);
		 orgRevVo.setOrgStatusEntity(statusEntityInfo);
		 orgRevVo.setAppFilesEntity(appFilesEntityInfo);
        
		return service.orgRevUpdate(baseId, orgRevVo);
		
	}
	
	@ApiOperation(value = "是否能够三定变更或部门撤并的校验", httpMethod = "GET", response = JSONObject.class, notes = "通过OrgId校验该机构是否能够三定变更或部门撤并")
    @RequestMapping(value = "3/{orgId}/check", method = RequestMethod.GET)
    public JSONObject orgCheck(HttpServletRequest request, HttpServletResponse response,
            @ApiParam(value = "orgId", required = true) @PathVariable("orgId") Integer orgId)
            throws RestClientException, Exception {
        return service.orgCheck(orgId);
    }

}
